package com.example.jikejavatrain.jvm.nio;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 创建http请求HttpServer01
 * @author fangzhuangzhan
 * @date 2021/08/15 13:54
 */
public class HttpClient01 {

    public static void main(String[] args) {
        httpClientWay();
        OkHttpWay("http://localhost:8801");
    }

    public static String OkHttpWay(String remoteUrl) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
            .url(remoteUrl)
            .build();
        String result = "调用失败";
        try {
            Response response = client.newCall(request).execute();

            if (response.isSuccessful()) {
                System.out.println("响应状态："+response.code());
                final String body = response.body().string();
                System.out.println("响应数据："+ body);
                result = body;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    private static void httpClientWay() {
        final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet("http://localhost:8801");

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            System.out.println("响应状态："+response.getStatusLine());
            System.out.println("响应数据："+ EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
